#include "UserInfoTable.h"
#include "Ext\FilterQuery.h"
#include "DatabaseException.h"


namespace TCServer
{
    namespace Store
    {

        void UserInfoTable::create()
        {
            FilterQuery q(R"(

            CREATE TABLE IF NOT EXISTS `usersinfo` (
              `id` bigint(20) unsigned NOT NULL,
              `headUrl` varchar(255) DEFAULT 'qrc:/resources/tests/335X335.jpg',
              `nickname` varchar(60) DEFAULT NULL,
              `createTime` datetime DEFAULT CURRENT_TIMESTAMP,
              PRIMARY KEY (`id`),
              UNIQUE KEY `id_UNIQUE` (`id`),
              KEY `index_nickname` (`nickname`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

			)");
            return q.exec();
        }

        quint64 UserInfoTable::insert(const Type::UserInfo &info)
        {
            FilterQuery q;
            q.prepare(R"(

            INSERT INTO `tc`.`usersinfo`
            (
            `id`,
            `headUrl`,
            `nickname`
            )
            VALUES
            (
            ?,
            ?,
            ?);

			)");
            q.addBindValue(info.id);
            q.addBindValue(info.headUrl);
            q.addBindValue(info.nickname);
            q.exec();
            return info.id;
        }

        TCServer::Type::UserInfo UserInfoTable::query(const quint64 id)
        {

            FilterQuery q;
            q.prepare(R"(

            SELECT `usersinfo`.`id`,
                `usersinfo`.`headUrl`,
                `usersinfo`.`nickname`,
                `usersinfo`.`createTime`
            FROM `tc`.`usersinfo`
			WHERE `id` = ?;

			)");
            q.addBindValue(id);
            q.exec();

            if (!q.next())
                throw DatabaseLogicException(q);

            return Type::UserInfo{
                q.nextValue().toULongLong(),  //  `usersinfo`.`id`
                q.nextValue().toString(),     //  `usersinfo`.`headUrl`,
                q.nextValue().toString(),     //  `usersinfo`.`nickname`,
                q.nextValue().toDateTime(),   //  `usersinfo`.`createTime`,
            };
        }

        void UserInfoTable::update(const Type::UserInfo &user)
        {
            FilterQuery q;
            q.prepare(R"(

                UPDATE `tc`.`usersinfo`
                SET
                `headUrl` = ?,
                `nickname` = ?,
                `createTime` =?
                WHERE `id` = ?;

			)");
            q.addBindValue(user.headUrl);
            q.addBindValue(user.nickname);
            q.addBindValue(user.creationTime);
            q.addBindValue(user.id);
            q.exec();
        }

        void UserInfoTable::remove(quint64 id)
        {
            FilterQuery q;
            q.prepare(R"(

                DELETE FROM `tc`.`usersinfo`
                WHERE `id` = ?;

			)");
            q.addBindValue(id);
            q.exec();
        }

    }
}
